<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Alipay extends Auth_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model("user_model","user");
        $this->load->model("point_model","point");
    }

    public function test()
    {
        $json_content = urldecode(file_get_contents('php://input')) ? urldecode(file_get_contents('php://input')) : 'clientOs=1';
        file_put_contents("tixian.txt", date("Y-m-d H:i:s", time())."--".$json_content."\r\n",FILE_APPEND);
        // $params['amount'] = $this->queryData["amount"];
        $params['amount'] = 1;
        $validate = new Validate([
            'amount' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $userInfo = $this->userDetail;
        //查询当前用户的总金额
        if($params['amount'] > $userInfo['money'])
        {
            $this->errorCode = 90012;
            $this->createApi();
            exit;
        }
        try {
                $payResult = $this->payToUser($openid, "提现成功", $params['amount']);die;
                file_put_contents("tixian.txt", date("Y-m-d H:i:s", time())."--result:".$payResult."\r\n",FILE_APPEND);

                if($payResult['return_code'] != "SUCCESS")
                {
                    throw new Exception($payResult['return_msg']);
                    
                }
                //添加提取现金记录
                $payData = [
                            'money'=>$params['amount']*-1,
                            'AccountID'=>$userInfo['AccountID'],
                            'type'=>13,
                            'createtime'=>date("Y-m-d",time()),
                            'correcttime'=>time()
                        ];      
                $res = $this->point->addAnswerMoney($payData);
            $this->createApi();exit;  
        } catch (Exception $e) {
            $this->errorCode = 90013;
            $this->errorMessage = $e->getMessage;
            $this->createApi();exit;
        }
        
    }
    

    private function payToUser()
    {
        require_once(APPPATH.'third_party/alipaysdk/aop/AopClient.php');
        require_once(APPPATH.'third_party/alipaysdk/aop/request/AlipayFundTransToaccountTransferRequest.php');

        $aop = new AopClient(); 
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; 
        $aop->appId = '2016xxxxxxxxxxx'; 
        $aop->rsaPrivateKey = 'xxxxxxxxx'; 
        $aop->alipayrsaPublicKey='xxxxxx'; 
        $aop->apiVersion = '1.0'; 
        $aop->signType = 'RSA2'; 
        $aop->postCharset='UTF-8'; 
        $aop->format='json'; 
        $request = new AlipayFundTransToaccountTransferRequest (); 
        $out = $this->random(32, 1); 
        var_dump($out); 
        $request->setBizContent("{" . 
         "    \"out_biz_no\":\"$out\"," . 
         "    \"payee_type\":\"ALIPAY_LOGONID\"," . 
         "    \"payee_account\":\"18983474834\"," . 
         "    \"amount\":\"0.10\"," . 
         "    \"payer_show_name\":\"快猎网络打款\"," . 
         "    \"payee_real_name\":\"张三\"," . 
         "    \"remark\":\"66666\"" . 
         "  }"); 
        $result = $aop->execute ($request); 
        var_dump($result); 
        $respond = str_replace(".", "_", $request->getApiMethodName()) . "_response"; 
        $resultCode = $result->$respond->code; 
        if(!empty($resultCode)&&$resultCode == 10000){ 
         echo "成功"; 
        } else { 
         echo "失败"; 
        } 

    }

public function random($length, $type = 0, $hash = '') { 
 if ($type == 0) { 
 $chars = '0123456789abcdefghijklmnopqrstuvwxyz'; 
 } else if ($type == 1) { 
 $chars = '123456789'; 
 } else if ($type == 2) { 
 $chars = 'abcdefghijklmnopqrstuvwxyz'; 
 } 
 $max = strlen($chars) - 1; 
 mt_srand((double) microtime() * 1000000); 
 for ($i = 0; $i < $length; $i++) { 
 $hash.= $chars[mt_rand(0, $max)]; 
 } 
 return $hash; 
} 
   
}
